import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class RealTimeChart extends ChartPanel implements Runnable {

    private static final long serialVersionUID = 1L;
    private static TimeSeries timeSeries;
    private double random_number;
    public void getrandom_number(double random_number){
        this.random_number = random_number;
    }

    public RealTimeChart(String chartContent, String title, String yAxisName) {
        super(createChart(chartContent, title, yAxisName));
    }

    private static JFreeChart createChart(String chartContent, String title, String yAxisName) {
        timeSeries = new TimeSeries(chartContent);
        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(timeSeries);
        JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "时间(秒)", yAxisName, timeseriescollection, true, true, false);
        ValueAxis valueaxis = jfreechart.getXYPlot().getDomainAxis();
        valueaxis.setAutoRange(true);
        valueaxis.setFixedAutoRange(30000D);
        return jfreechart;
    }

    @Override
    public void run() {
        while(true){
            try {
                timeSeries.addOrUpdate(new Millisecond(), random_number);
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }

    }

//    public static void main(String[] args) {
//        // 设置显示样式，避免中文乱码
////        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
////        standardChartTheme.setExtraLargeFont(new Font("微软雅黑", Font.BOLD, 20));
////        standardChartTheme.setRegularFont(new Font("微软雅黑", Font.PLAIN, 15));
////        standardChartTheme.setLargeFont(new Font("微软雅黑", Font.PLAIN, 15));
////        ChartFactory.setChartTheme(standardChartTheme);
//        JFrame frame = new JFrame("动态随机数折线图");
//        RealTimeChart realTimeChart = new RealTimeChart("随机数折线图", "随机数", "数值");
//        frame.getContentPane().add(realTimeChart, new BorderLayout().CENTER);
//        frame.pack();
//        frame.setVisible(true);
//        (new Thread(realTimeChart)).start();
//        frame.addWindowListener(new WindowAdapter() {
//            @Override
//            public void windowClosing(WindowEvent windowevent) {
//                System.exit(0);
//            }
//        });
//    }
}